package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.BaseInfoDto;
import com.itheima.ydd.dto.CateDto;
import com.itheima.ydd.dto.SysUserDto;
import com.itheima.ydd.entity.SysConfig;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.entity.YddArticle;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/index")
@CrossOrigin
@Slf4j
public class IndexController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IYddArticleService articleService;


    @Autowired
    private IYddAdvposService advposService;

    @Autowired
    private IYddTagService tagService;

    @Autowired
    private IYddAdvimgService advimgService;

    @Autowired
    private IYddUserService yddUserService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IYddCateService cateService;
    @Autowired
    private IIndexService indexService;
    @Autowired
    private IYddArticleService iYddArticleService;


    @GetMapping("new")
    public ResultData findPage(String page,String limit){
        return   iYddArticleService.findPage(page,limit);

    }

    @GetMapping("list")


    public ResultData findArticleList(String page,String limit,String cateid){
        return   iYddArticleService.findArticleList(page,limit,cateid);

    }

    @GetMapping("/hot")
    public ResultData findHot(){
        return   iYddArticleService.findHot();

    }

    @GetMapping("/recommend")
    public ResultData findRecommend(){
        return   iYddArticleService.findRecommend();

    }












    @PostMapping("/login")

    public R login(@RequestBody SysUser sysUser) {
        log.info("登陆用户：{}", sysUser.toString());


        String loginName = sysUser.getLoginName();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getLoginName, loginName);
        SysUser one = sysUserService.getOne(wrapper);

        if (one == null) {
            return R.error("账号不存在");
        } else if (one.getStatus() == 0) {
            return R.error("账号已禁用");
        }

        String password = sysUser.getPassword();
        if (one.getPassword().equals(generatePassword(password))) {
            //把用户id 加密进token里

            // 生成token信息
            Map retMap = new HashMap();
            Map tokenMap = new HashMap<>();
            String roleId = one.getRoleId()
                    .replace("[", "")
                    .replace("]", "")
                    .replace("\"", "");

            tokenMap.put("userId", one.getId());
            tokenMap.put("roleId", roleId);

            String token = JwtUtils.getToken(tokenMap);
            retMap.put("token", token);
            return R.success("token", JwtUtils.getToken(tokenMap));
        }
        return R.error("密码错误");

    }

    @GetMapping("/getConfig")
    public R systemConfig() {
        LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysConfig::getTabValue, "system");
        List<SysConfig> sysConfigs = sysConfigService.list(wrapper);

        HashMap<String, String> map = new HashMap<>();
        for (SysConfig sysConfig : sysConfigs) {
            map.put(sysConfig.getAttrKey(), sysConfig.getAttrValue());
        }

        return new R(map, "", 0);

    }

    @PostMapping("/profile")
    @CrossOrigin
    public R profile(HttpServletRequest request) {
        String token = request.getHeader("x-token");

        Claims claims = JwtUtils.getClaims(token);
        Long userId = Long.valueOf((String) claims.get("userId"));

        log.info("用户id:{}", userId);
        return sysUserService.profile(userId);
    }

    /**
     * md5加密
     *
     * @param password 密码
     */
    private String generatePassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }

    @GetMapping("/baseInfo")
    public ResultData baseInfo(HttpServletRequest request) {
        BaseInfoDto baseInfoDto = new BaseInfoDto();
        baseInfoDto.setArticleNum(0);

        // 所有分类数据
        List<CateDto> cateDtoList = cateService.list().stream().map(cate -> {
            CateDto cateDto = new CateDto();
            BeanUtils.copyProperties(cate, cateDto);
            LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(YddArticle::getCateid, cate.getId());
            int count = articleService.count(queryWrapper);
            cateDto.setNum(count);

            // 文章总数
            baseInfoDto.setArticleNum(baseInfoDto.getArticleNum() + count);
            return cateDto;
        }).collect(Collectors.toList());
        baseInfoDto.setAllCateList(cateDtoList);


        // 广告位总数
        baseInfoDto.setAdvposNum(advposService.count());

        // 标签总数
        baseInfoDto.setTagNum(tagService.count());

        // 管理员总数
        baseInfoDto.setAdminNum(userService.count());

        // 广告分类总数
        baseInfoDto.setCateNum(cateDtoList.size());

        // 广告图总数
        baseInfoDto.setAdvimgNum(advimgService.count());

        {
            // 最新用户数据
            LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(YddUser::getId, YddUser::getUsername, YddUser::getSex, YddUser::getAddress, YddUser::getIcon);
            // 默认数据
            queryWrapper.orderByDesc(YddUser::getId);
            queryWrapper.last("limit 7");

            baseInfoDto.setNewUserList(yddUserService.list(queryWrapper));
        }


        // 热门文章数据
        {
            LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(YddArticle::getId, YddArticle::getTitle, YddArticle::getAuthor, YddArticle::getKeywords, YddArticle::getClick);
            queryWrapper.orderByDesc(YddArticle::getClick);
            queryWrapper.last("limit 7");
            baseInfoDto.setHotArticleList(articleService.list(queryWrapper));
        }


        {
            // 用户数据
            SysUserDto userDto = new SysUserDto();
            LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(YddUser::getSex, 0);
            int womanNum = yddUserService.count(queryWrapper);
            int allNum = yddUserService.count();
            userDto.setTotal(allNum);
            userDto.setUserWoman(womanNum);
            userDto.setUserMan(allNum - womanNum);
            baseInfoDto.setUser(userDto);
        }
        return ResultData.ok("", baseInfoDto);
    }
    /**
     * 首页和全局数据
     * @return
     */
    @GetMapping("index")
    public ResultData index(){
         ResultData resultData = indexService.index();
        return resultData;
    }

    /**
     * 文章详情数据
     * @param id
     * @return
     */
    @GetMapping("show")
    public ResultData show(String id){
        return iYddArticleService.show(id);
    }

@PostMapping("reg")
public ResultData reg(@RequestBody Map<String,String> params){
    return  yddUserService.reg(params);
}


}


